package com.liu.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.liu.pojo.Role;
import com.liu.pojo.User;
import com.liu.service.role.RoleService;
import com.liu.service.role.RoleServiceImpl;
import com.liu.service.user.UserService;
import com.liu.service.user.UserServiceImpl;
import com.liu.util.PageSupport;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.liu.util.Constants;
//import sun.jvm.hotspot.debugger.Page;

//实现servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method!=null && method.equals("updatePassword")){
            this.updatePwd(req,resp);
        }else if(method!=null && method.equals("pwdmodify")){
            this.pwdmodify(req,resp);
        } else if (method!=null && method.equals("query")) {
            try {
                this.query(req,resp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        //从session里获取id
//        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
//        String newpassword = req.getParameter("newpassword");
//
//        boolean flag = false;
//
//        if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
//            UserService userService = new UserServiceImpl();
//            flag = userService.updatePwd(((User) o).getId(), newpassword);
//            if (flag){
//                req.setAttribute("message", "修改密码成功，请退出并使用新密码登录！");
//                //密码修改成功后，移除session
//                req.getSession().removeAttribute(Constants.USER_SESSION);
//            }else {
//                req.setAttribute("message", "修改密码失败！");
//            }
//        }else {
//            req.setAttribute("message", "新密码设置格式错误");
//        }
//
//        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session里获取id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag = false;

        if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if (flag){
                req.setAttribute("message", "修改密码成功，请退出并使用新密码登录！");
                //密码修改成功后，移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message", "修改密码失败！");
            }
        }else {
            req.setAttribute("message", "新密码设置格式错误");
        }

        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }

    //验证旧密码，session中有用户的密码
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session中获取id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map
        Map<String,String> resultMap = new HashMap<String,String>();
        if(o == null){
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
            resultMap.put("result","error");
        }else{
            String userPassword = ((User) o).getUserPassword();
            if (!userPassword.equals(oldpassword)){//旧密码错误
                resultMap.put("result","error");
            }else{
                resultMap.put("result","true");
            }
        }

        try{
            resp.setContentType("application/json");
//            resp.setContentType("text/html");
//            resp.setContentType("text/javascript");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void query(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //从前端获取参数
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserService userService = new UserServiceImpl();
        List<User> userList = null;

        //
        int pageSize = 5;
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);
        }
        if(pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //控制页面不能小于1
        if(currentPageNo < 1) {
            currentPageNo = 1;
        }

        //获取用户总数
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);

        //总页数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);//每页显示的记录数
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();

        //控制层对数据进行分页

        if (currentPageNo<1){
            currentPageNo=1;
        } else if (currentPageNo>totalPageCount) {
            currentPageNo=totalPageCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);

        //返回前端
        req.getRequestDispatcher("userlist.jsp").forward(req, resp);
    }
}


